package au.com.handsunited.web.validator.user;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import au.com.handsunited.model.User;
import au.com.handsunited.model.validators.entity.UserValidator;
import au.com.handsunited.service.UserService;
import au.com.handsunited.web.command.user.UserCommand;
import au.com.handsunited.web.command.user.UserSearchCommand;

/**
 * @author Arun Chandrasekhar
 * @date 05/01/2007 10:23:21 AM
 */
public class UserCommandValidator implements Validator {

	private final UserService userService;
	private final UserValidator userValidator;

	private static Logger logger = LoggerFactory.getLogger(UserCommandValidator.class);


	public UserCommandValidator(UserService userService, UserValidator userValidator) {
		this.userService = userService;
		this.userValidator = userValidator;
	}


	/**
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	public boolean supports(Class clazz) {
		return clazz.isAssignableFrom(UserCommand.class);
	}

	/**
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	public void validate(Object command, Errors errors) {

		UserCommand userCommand = (UserCommand) command;
		User user = userCommand.getUser();

		try {
			errors.pushNestedPath("user");
			ValidationUtils.invokeValidator(userValidator, user, errors);
		} finally {
			errors.popNestedPath();
		}

		User u = userService.findUserByUsername(user.getUsername());
		if ((u != null) && !user.getId().equals(u.getId())) {
			errors.rejectValue("user.username", "username.exists", "Username exists.");
		}
	}

}
